<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * 后台管理员管理模型类
 * @author 66diqiu-li
 *
 */
class Admin_Adminuser_model extends CI_Model {

	/**
	 * @var 表名称
	 */
	private $table;
	private $sid;
	private $table_division;
    private $table_cash_log;


	public function __construct()
	{
		parent::__construct();
		$this->sid = $GLOBALS['sid'];
		$this->table  = $this->db->dbprefix("admin_user");
		$this->table_division= $this->db->dbprefix("division");
        $this->table_cash_log= $this->db->dbprefix("admin_user_cash_log");
	}

	/**
	 * 更新数据
	 * @param $data 数据数组
	 * @param $where 更新条件
	 * @param bool $nosid
	 * @return mixed
	 */
	function edit_row($data,$where, $nosid = false){
		if(!$nosid)$where['sid'] = $GLOBALS['sid'];
		$this->db->where($where, NULL, FALSE);
		return $this->db->update($this->table,$data);
	}

	/**
	 * 添加数据
	 * @param $data
	 * @return bool
	 */
	function add_row($data){
		if(empty($data['sid']))$data['sid'] = $GLOBALS['sid'];
		if(is_array($data)){
			if($this->db->insert($this->table,$data)){
				return $this->db->insert_id();
			}else{
				return false;
			}
		}
	}

	/**
	 * 获取单条记录
	 * @param array $where 查询条件
	 * @param string $field 显示字段
	 * @return mixed
	 */
	function get_row($where=array(),$field='*'){
		if(!empty($field))$this->db->select($field);
		if(!isset($where['sid']))$where['sid'] = $GLOBALS['sid'];
		$query = $this->db->get_where($this->table,$where,1);
		return $query->row_array();
	}

	function check_exist($where=array(),$field='*'){
		if(!empty($field))$this->db->select($field);
		$query = $this->db->get_where($this->table,$where,1);
		return $query->row_array();
	}

	/**
	 *
	 * 删除数据
	 * @param array $where 删除条件
	 */
	function remove_row($where=array()){

        if(!empty($where)&&is_array($where)){
            return $this->db->delete($this->table,$where);
        }elseif(is_string($where)){
            $this->db->where($where, NULL, FALSE);
            return $this->db->delete($this->table);
        }
        return false;
	}

	/**
	 * 获取所有管理管理员
	 * @param int $page_size 每页显示数量
	 * @param int $now_page 第几页
	 * @param $where 选择条件
	 * @return array
	 */
	function get_list($page_size=20,$now_page=1,$where){
		$table = $this->table;
		$this->db->select($table.'.id,'.$table.'.name,'.$table.'.email,'.$table.'.is_open,'.$table.'.is_diy,'.$table.'.mobile,'.$table.'.add_time,'.$table.'.last_login_time,'.$table.'.last_login_ip,'.$table.'.division_id');
		//$this->db->select($this->table_division.'.name as division_name');
//		$where[$table.'.sid'] = $GLOBALS['sid'];
		if(!empty($where))$this->db->where($where, NULL, FALSE);
		$this->db->select($this->db->dbprefix("admin_role").'.name as role_name');
		$this->db->join($this->db->dbprefix("admin_role"), $this->db->dbprefix('admin_role').".id=$table.role_id");
		//$this->db->join($this->table_division,$this->table_division.".id=$table.division_id");
		$query = $this->db->get($this->table,$page_size,($now_page-1)*$page_size);
		$data = array();
		foreach($query->result_array() as $row){
			$row['remove_url'] = site_url('admin/adminuser/ajax_remove?id='.$row['id']);
			$row['edit_url'] = site_url('admin/adminuser/edit?id='.$row['id']);
			$row['auth_url']   =  site_url('admin/adminuser/division_auth?id='.$row['id']);
			$row['division_name'] = '总部';
			if($row['division_id']>0){
				$division = $this->division_row(array('id'=>$row['division_id']),'name');
				$row['division_name'] = $division['name'];
			}
			$data[] = $row;
		}
		return $data;
	}

	/**
	 *
	 * 获取总数量
	 * @param array $where 查询条件
	 */
	function get_count($where=array()){
//		$where['sid'] = $GLOBALS['sid'];
        $this->db->where($where, NULL, FALSE);
		$this->db->select('id');
		$this->db->from($this->table);
		return $this->db->count_all_results();
	}

	/**
	 * 验证码管理员登陆
	 * @param $identifier
	 * @param $password
	 * @return bool
	 */
	function login($identifier,$password, $return = false){
		if(empty($identifier)||empty($password)){
			return false;
		}

		/*超全局管理员，登录成功后进入站点管理平台。*/
		if($userInfo = $this->get_row(array('name'=>$identifier,'password'=>md5($password), 'sid' => -1)))
		{
			$this->registerLogin($userInfo);
			if($return) {
				return $userInfo['id'];
			}else{
				redirect('admin/site/index');
			}
		}

		//验证
		$userInfo = $this->get_row(array('name'=>$identifier,'password'=>md5($password)));
		if(empty($userInfo)){
			$userInfo = $this->get_row(array('email'=>$identifier,'password'=>md5($password)));
		}
		if(empty($userInfo)){
			$userInfo = $this->get_row(array('mobile'=>$identifier,'password'=>md5($password)));
		}
		if (false == $userInfo) {
			//记录登录日志
			$this->_record($identifier, 0);
			return false;
		}
		//记录登录日志
		$this->_record($identifier, 1);

		//注册登录状态
		$this->registerLogin($userInfo);
		return $userInfo['id'];
	}

	/**
	 * 注册用户登录状态
	 * @param array $userInfo 用户信息
	 * @return bool
	 */
	function registerLogin($userInfo=array()){
		//写入session
		$newdata = array(
            'admin_user_id' => $userInfo['id'],
            'admin_user_name' => $userInfo['name'],
			'admin_role_id' =>$userInfo['role_id'],
            'supplier_id'=>$userInfo['supplier_id'],
            'sid' => $GLOBALS['sid'],
            'adminid' => $userInfo['id'],
		    'authority'=>$userInfo['authority'],
            'is_diy'=>$userInfo['is_diy'],
		);
		$this->session->set_userdata($newdata);

		//更新登录信息
		$update_data = array(
            'last_login_time' => date('Y-m-d H:i:s',now()),
            'last_login_ip' => get_client_ip(),
		);

		$this->edit_row($update_data,array('id'=>$userInfo['id']));

        if($userInfo['sid']==-1){
            $accessList = 'ALL';
        }else{
            //注册权限
            $this->load->model('admin.Adminrole_model');
            $roleinfo = $this->Adminrole_model->get_row(array('id'=>$userInfo['role_id']));
            if (empty($roleinfo) || empty($roleinfo['status'])) {
                return false;
            }

            //该角色全部权限
            if(trim($roleinfo['name'])!='超级管理员'){//超级管理权限
                $this->load->model('admin.Adminroleauthors_model');
                $access = $this->Adminroleauthors_model->get_list(array('role_id'=>$userInfo['role_id']));
                $accessList = '';
                foreach($access as $val){
                    $accessList.= ','.$val['app'].'/'.$val['controller'].'/'.$val['action'];
                }
                $accessList = substr($accessList,1);
            }else{
                $accessList = 'ALL';
            }
        }


		$data = array(
            '_ACCESS_LIST' => $accessList,
		);
		$this->session->set_userdata($data);
	}

	/**
	 *
	 * 退出
	 */
	public function logout() {
		$this->session->sess_destroy();
		return true;
	}

	/**
	 * 记录管理员登录日志
	 * @param $identifier 用户名
	 * @param int $status 状态
	 */
	private function _record($identifier, $status = 0){
		$this->load->model('admin.Adminloginlog_model');
		$data = array(
    	    'username' => $identifier,
    	    'login_time' => date('Y-m-d H:i:s',now()),
    	    'login_ip' => get_client_ip(),
    	    'status' => $status
		);
		$data['sid'] = $GLOBALS['sid'];
		$this->Adminloginlog_model->add_row($data);
	}

	/**
	 *
	 * 判断管理员是否登陆
	 */
	function is_login(){
		$admin_user_id = $this->session->userdata('admin_user_id');
		if(empty($admin_user_id))redirect(site_url('admin/index/login'));
		return true;
	}

	/**
	 * 返回查询条件
	 * @param $where 查询条件
	 * @return array|string
	 */
	function set_where($where){
		if(is_array($where))$where['sid']=$this->sid;
		else $where=$where?$where.' AND sid='.$this->sid:'sid='.$this->sid;
		return $where;
	}
	/**
	 * 获取所有管理菜单
	 * @param array $where
	 * @return array
	 */
	function division_list($where=array()){
		//站点配置信息
		$this->db->select('*');
		$where['sid']=$this->sid;
		$this->db->where($where, NULL, FALSE);
		$this->db->order_by('sort_order', 'ASC');
		$query = $this->db->get($this->table_division);
		$data  = $query->result_array();
		return $data;
	}
	function division_add($data){
		if(empty($data['sid']))$data['sid'] = $this->sid;
		if(is_array($data)){
			if($this->db->insert($this->table_division,$data)){
				return $this->db->insert_id();
			}else{
				return false;
			}
		}
	}

	function update_code($id,$pid){
		
		if($pid){
			$pcode = $this->division_row(array('id'=>$pid),'code');
			$sql = "update ".$this->table_division." set code=concat($pcode[code],',',$id) where id=$id";
		}else{
			$sql = "update ".$this->table_division." set code=$id where id=$id";
		}
		return $this->db->query($sql);
	}
	function division_edit($data,$where){
		if(!empty($where))$this->db->where($where, NULL, FALSE);
		return $this->db->update($this->table_division,$data);
	}

	/**
	 * 查询该部门是否有子分类部门
	 * @param $parent_id
	 * @return bool
	 */
	function is_has_child($parent_id){
		$this->db->select('id');
		$query = $this->db->get_where($this->table_division,array('parent_id'=>$parent_id),1);
		$row = $query->row();
		if(isset($row->id)&&$row->id){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 获取单条记录
     * @param array $where
     * @param string $field
     * @return mixed
	 */
	function division_row($where=array(),$field='*'){
	    if(!empty($field))$this->db->select($field);
	    $query = $this->db->get_where($this->table_division,$where,1);
	    return $query->row_array();
	}
	
	/**
	 * 删除数据
     * @param array $where
     * @return bool
	 */
	function division_remove($where=array()){
		if(!empty($where)){
		    return $this->db->delete($this->table_division,$where);
		}
		return false;
	}
	
	function admin_list_option($id){
		$auth = $this->session->userdata('authority')?$this->session->userdata('authority'):0;
		$sql = "select id,name from ".$this->table." where division_id in ($auth)";
		$query = $this->db->query($sql);
		$list = $query->result_array();
		$str='';
		foreach($list as $key=>$val){
			if($val['id']==$id){
				$str.= '<option value="'.$val['id'].'" selected>'.$val['name'].'</option>';
			}else{
				$str.= '<option value="'.$val['id'].'">'.$val['name'].'</option>';
			}
		}
		return $str;
	}
	
    /**
     * 添加资金管理日志并修改资金信息
     * @param $data
     * @return bool
     */
    public function add_cash_log($data){

        //资金管理操作日志
        $log_id = $this->db->insert($this->table_cash_log,$data);
        if($log_id){
            //资金类型
            if($data['cash_type']==1){
                $column = 'cash_deposit';
            }elseif($data['cash_type']==2){
                $column = 'cash_pledge';
            }elseif($data['cash_type']==3){
				$column = 'cash_commision';
			}

			if(isset($data['status'])&&($data['status']==0)){
				return true;//status默认为1，如果为0表示佣金提现，不更新会员表
			}

            //调整类型
            if($data['type']==1){
                $type = '+';
            }elseif($data['type']==2){
                $type = '-';
            }
            $sql = "UPDATE {$this->table} SET {$column}={$column}{$type}{$data['money']} WHERE id={$data['user_id']}";
            $res = $this->db->query($sql);
            if(!$res){
                $this->db->delete($this->table_cash_log,array('id'=>$log_id));
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    /**
     * 获取所有资金管理操作日志
     * @param int $page_size 每页显示数量
     * @param int $now_page 第几页
     * @param string $where 选择条件
     * @return array
     */
    function get_cash_list($page_size=20,$now_page=1,$where = ''){
        $this->db->select('id,add_admin_username,money,type,cash_type,add_time,remark,status');
        $this->db->order_by('add_time','DESC');
        if(!empty($where)){
            $this->db->where($where, NULL, FALSE);
        }
        $query = $this->db->get($this->table_cash_log,$page_size,($now_page-1)*$page_size);
        $data = array();
        foreach($query->result_array() as $row){
            $data[] = $row;
        }
        return $data;
    }

	/**
	 * 获取所有佣金提现申请日志
	 * @param int $page_size 每页显示数量
	 * @param int $now_page 第几页
	 * @param string $where 选择条件
	 * @return array
	 */
	function get_cash_commision($page_size=20,$now_page=1,$where = ' and a.type=2 '){
		$start = ($now_page-1)*$page_size;
		$sql = " select a.id,a.add_admin_username,a.money,a.type,a.cash_type,a.add_time,a.remark,a.status,b.name,b.bank,b.bank_info,b.card_name,b.card_number from $this->table_cash_log as a ";
		$sql.= " left join $this->table as b on b.id=a.user_id ";
		$sql.= " where a.cash_type=3 $where and a.sid=$this->sid ";//

		$query_total = $this->db->query($sql);
		$total = $query_total->num_rows();
		$sql .= " order by a.add_time desc limit $start,$page_size ";
		$query = $this->db->query($sql);
		$list =  $query->result_array();
		return array('total'=>$total,'list'=>$list);
	}

    /**
     *
     * 获取总数量
     * @param array $where 查询条件
     */
    function get_cash_count($where=array()){
        $this->db->select('id');
        $this->db->from($this->table_cash_log);
        if(!empty($where))$this->db->where($where, NULL, FALSE);
        return $this->db->count_all_results();
    }

    function  get_child_divisions($id){
        $sql = "select id from $this->table_division where find_in_set($id,code)";
        $query = $this->query($sql);
        $list = $query->result_array();
    }

	/**
	 * 确认提现申请
	 * @param $id
	 */
	function edit_cash_log_status($id){
		$data = $this->get_cash_info(array('id'=>$id));
		if($data['cash_type']!=3||$data['status']==1){
			return false;
		}
		$this->db->query("update $this->table_cash_log set status=1 where id=$id");
		$sql = "UPDATE {$this->table} SET cash_commision=cash_commision-{$data['money']} WHERE id={$data['user_id']}";
		$res = $this->db->query($sql);
		return $res;
	}

	/**
	 * 获取单条金额记录
	 * @param array $where
	 * @param string $field
	 * @return mixed
	 */
	function get_cash_info($where=array(),$field='*'){
		if(!empty($field))$this->db->select($field);
		$query = $this->db->get_where($this->table_cash_log,$where,1);
		return $query->row_array();
	}
}